﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using ICeFramework.Common.Attributes;

namespace ICeFramework.Common.Extenstions
{
    public static class TypeExtensions
    {
        public static PropertyInfo[] GetFilteredProperties(this Type type)
        {
            return type.GetProperties().Where(pi => !Attribute.IsDefined(pi, typeof(SkipPropertyAttribute))).ToArray();
        }

        public static PropertyInfo[] GetFilteredProperties(this Type type, BindingFlags bindingAttr)
        {
            return type.GetProperties(bindingAttr).Where(pi => !Attribute.IsDefined(pi, typeof(SkipPropertyAttribute))).ToArray();
        }

        public static T Parse<T>(this object value)
        {
            try
            {
                Type type = typeof(T);

                if (type.Name == "Nullable`1")
                    type = Nullable.GetUnderlyingType(type);

                if (type.BaseType.Name == "Enum" || (type.Name == "Enum"))
                    return (T)Enum.Parse(type, value.ToString().Replace(" ", ""));

                if (type.Name == "Guid")
                    return (T)(object)(new Guid(value.ToString()));

                return (T)Convert.ChangeType(value, type);
            }
            catch (Exception) { return default(T); }
        } 
    }
}
